﻿Imports System.Net
Imports System.Web.Http


Public Class apiHelpers

    ''' <summary>
    ''' Manager Exceptions throw in API
    ''' </summary>
    ''' <param name="ex"></param>
    ''' <remarks></remarks>
    Public Shared Sub ManageException(ex As Exception)

        Dim message As String = ex.Message
        While (ex.InnerException IsNot Nothing)
            message = message & " " & ex.InnerException.Message
            ex = ex.InnerException
        End While

        Dim httpEx As New Http.HttpResponseMessage(HttpStatusCode.OK)
        httpEx.Content = New Http.StringContent(New APiError(message).ToString())
        Throw New HttpResponseException(httpEx)


    End Sub
End Class

''' <summary>
''' Error message from API
''' </summary>
''' <remarks></remarks>
Public Class APiError
    Public hasError As Boolean = True
    Public [error] As String

    Sub New(message As String)
        Me.error = message.Replace("""", "").Replace("'", "")
        Me.error = Me.error.Replace(Chr(10), "").Replace(Chr(13), "")
        ''Me.error = Me.error.Replace("\", "")
        Me.error = System.Web.HttpContext.Current.Server.UrlEncode(Me.error)

    End Sub

    Public Overrides Function ToString() As String
        Return "{""hasError"":true,""error"":""" & Me.error & """}"
    End Function


End Class